from Lib.SerialPort import *
from Lib.crc16 import *
from Lib.Utils import *
import datetime
import time
import os
import threading

class Borad75(object):
    def __init__(self):
        self.listTemp1 = []
        self.temp1 = None
        self.temp2 = None
        self.workFlag=False
        self.seria = None
        self.theadBorad = threading.Thread(target=self.work)
        self.theadBorad.start()

        
    def readTem(self):
        self.seria.Write("#~000~qst~handshake~@".encode())
        encodestr = bytes.decode(self.seria.Read())
        self.temp1 = round(float(((encodestr.split(','))[0]).split(':')[1]),3)
        self.temp2 = round(float(((encodestr.split(','))[1]).split(':')[1]),3)
        return [self.temp1,self.temp2]

    def start(self):
        self.workFlag=False

    def stop(self):
        self.workFlag=False

    def work(self):
        while True:
            try:
                self.readTem()
                if(len(self.listTemp1)==300):
                    del self.listTemp1[0]
                self.listTemp1.append(self.temp1)
                time.sleep(1)
            except :
                pass

    def getStableTemp1(self):
        try:
            if(len(self.listTemp1)<300):
                return None
            else:
                if(max(self.listTemp1)-min(self.listTemp1)>0.2):
                    return None
                else:
                    return float(sum(self.listTemp1)) / len(self.listTemp1)
        except :
            return None
    def getVagTemp1(self):
        try:
            if(len(self.listTemp1)<60):
                return None
            else:
                return float(sum(self.listTemp1[-60:])) / len(self.listTemp1[-60:])
        except :
            return None
    def getMaxTemp1(self):
        try:
            if(len(self.listTemp1)<300):
                return None
            else:
                return max(self.listTemp1[:200])
        except :
            return None
